package com.milk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.milk.context.BaseContext;
import com.milk.dto.CommonPageQueryDTO;
import com.milk.entity.Category;
import com.milk.entity.Milktea;
import com.milk.exception.BaseException;
import com.milk.mapper.CategoryMapper;
import com.milk.mapper.MilkteaMapper;
import com.milk.result.PageResult;
import com.milk.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 奶茶分类 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-27
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private MilkteaMapper milkteaMapper;

    /**
     * 查询所有分类
     * @return
     */
    public List<Category> selectALl() {

        return categoryMapper.selectList(new QueryWrapper<>());

    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    public PageResult pageQuery(CommonPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<Category> page = categoryMapper.pageQuery(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增分类
     * @param category
     */
    public void insertCategory(Category category) {
        category.setStatus(1);
        category.setCreateTime(LocalDateTime.now());
        category.setCreateUser(BaseContext.getCurrentId());
        categoryMapper.insert(category);
    }

    /**
     * 删除分类
     * @param ids
     */
    public void deleteByIds(List<Long> ids) {
        //查看是否还有此奶茶的分类 如果有 不运行删除
        QueryWrapper<Milktea> qw = new QueryWrapper<>();
        qw.in("category_id",ids);
        List<Milktea> list = milkteaMapper.selectList(qw);
        if (list!=null && !list.isEmpty()){
            throw new BaseException("存在此分类的奶茶，无法删除");
        }

        categoryMapper.deleteByIds(ids);
    }

    /**
     * 修改分类
     * @param category
     */
    public void updateCategory(Category category) {
        if (category.getStatus()!=null && category.getStatus()== 0 ){
            QueryWrapper<Milktea> qw = new QueryWrapper<>();
            qw.eq("category_id",category.getId());
            List<Milktea> list = milkteaMapper.selectList(qw);
            log.info("list = {}",list);
            if (list != null && !list.isEmpty()){
                throw new BaseException("该分类下的奶茶有启用的，无法禁用");
            }
        }

        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(BaseContext.getCurrentId());
        categoryMapper.updateById(category);
    }
}
